#define _CRT_SECURE_NO_WARNINGS
#include"slist.h"

ListNode* ByNode(x)
{
	struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
	newnode->_next = NULL;
	newnode->_prev = NULL;
	newnode->_data = x;
	return newnode;
}

ListNode* ListCreate()
{
	struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
	head->_next = head;
	head->_prev = head;
	return head;
}

void ListPushBack(ListNode* phead, LTDataType x)
{
	/*assert(phead);
	struct ListNode* newnode = ByNode(x);
	struct ListNode* tail = phead->_prev;
	tail->_next = newnode;
	newnode->_prev = tail;
	newnode->_next = phead;
	phead->_prev = newnode;*/

	ListInsert(phead, x);
}

void ListPrint(ListNode* phead)
{
	assert(phead);
	struct ListNode* cur = phead->_next;
	printf("<=>head<=>");
	while (cur != phead)
	{
		printf("%d<=>", cur->_data);
		cur = cur->_next;
	}
	printf("\n");
}

bool chcek_SL(ListNode* phead)
{
	if (phead->_next == phead)
		return true;
	else
		return false;
}

void ListPopBack(ListNode* phead)
{
	/*assert(phead);
	assert(!chcek_SL(phead));
	struct ListNode* tail = phead->_prev;
	tail->_prev->_next = phead;
	phead->_prev = tail->_prev;
	free(tail);
	tail = NULL;*/
	assert(!chcek_SL(phead));
	ListErase(phead->_prev);
}

void ListPushFront(ListNode* phead, LTDataType x)
{
	/*struct ListNode* newnode = ByNode(x);
	struct ListNode* cur = phead->_next;
	phead->_next = newnode;
	newnode->_prev = phead;
	newnode->_next = cur;
	cur->_prev = newnode;*/
	ListInsert(phead->_next, x);
}

void ListPopFront(ListNode* phead)
{
	/*assert(phead);
	assert(!chcek_SL(phead));
	struct ListNode* cur = phead->_next;
	cur->_prev = phead;
	phead->_next = cur->_next;
	free(cur);
	cur = NULL;*/
	assert(!chcek_SL(phead));
	ListErase(phead->_next);
}

ListNode* ListFind(ListNode* phead, LTDataType x)
{
	assert(phead);
	struct ListNode* cur = phead->_next;
	while (cur != phead)
	{
		if (cur->_data == x)
			return cur;
		cur = cur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* prev = pos->_prev;
	ListNode* newnode = ByNode(x);
	newnode->_next = pos;
	pos->_prev = newnode;
	prev->_next = newnode;
	newnode->_prev = prev;
}


void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->_prev;
	ListNode* next = pos->_next;
	prev->_next = next;
	next->_prev = prev;
	free(pos);
	pos = NULL;
}

void ListDestory(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->_next;
	while (cur != phead)
	{
		ListNode* next = cur->_next;
		free(cur);
		cur = NULL;
		cur = next;
	}
	phead->_next = phead;
	phead->_prev = phead;
}